<?php
namespace app\middleware;

use app\model\AdminMenu;
use app\model\AdminUserAction;
use app\util\ReturnCode;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AdminLog implements MiddlewareInterface {

    /**
     * 日志
     * @param Request $request
     * @param callable $next
     * @return Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function process(Request $request, callable $next): Response
    {
        $controller_data = explode("\\", $request->controller);
        $url = $controller_data[3];
        $action = $request->action;
        $app= $request->app;
        $url_action = $app."/".$url."/".$action;
        $menuInfo = (new AdminMenu())->where('url', $url_action)->find();
        if ($menuInfo) {
            $menuInfo = $menuInfo->toArray();
        } else {
            return json([
                'code' => ReturnCode::INVALID,
                'msg'  => '当前路由非法：' . $url_action,
                'data' => []
            ]);
        }
        $ApiAuth = $request->header('Api-Auth');
        if ($ApiAuth) {
            $userInfo = cache('Login' . $ApiAuth);
            if ($userInfo) {
                $userInfo = json_decode($userInfo, true);
            }
        }
        $obj = new AdminUserAction();
        $id_suffix =$obj->get_table_number();
        AdminUserAction::suffix($id_suffix)->insert([
            'action_name' => $menuInfo['title'],
            'uid'         => $userInfo['id']??0,
            'nickname'    => $userInfo['nickname']??"",
            'add_time'    => time(),
            'url'         => $url_action,
            'data'        => json_encode($request->all())
        ]);

        return $next($request);
    }
}
